package user03.controller;

import common05.common.Results;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

@RestController
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public Results handleError(HttpServletRequest request) {
        // 获取错误状态码
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (statusCode == HttpStatus.NOT_FOUND.value()) {
            return Results.not_found();
        } else if (statusCode == HttpStatus.FORBIDDEN.value()) {
            return Results.forbidden();
        } else if (statusCode == HttpStatus.METHOD_NOT_ALLOWED.value()) {
            return Results.method_not_allowed();
        } else if (statusCode == HttpStatus.UNAUTHORIZED.value()) {
            return Results.unauthorized();
        } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return Results.error();
        } else {
            return Results.error();
        }
    }

}
